package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.function.MyAsyncFunction;
import com.danan.realtime.pojo.TradeProvinceOrderWindow;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_10_trade_province_order_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_10_trade_province_order_window().init(
                4010,
                3,
                "DwsApp_10_trade_province_order_window",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 封装为pojo，处理重复数据
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanDs = toTradeProvinceOrderWindow(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TradeProvinceOrderWindow> aggDs = windowAndAgg(beanDs);
        // 3 补充维度信息
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultDs = extendDimInfo(aggDs);
        // 4 写入Clickhouse
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_PROVINCE_ORDER_WINDOW,TradeProvinceOrderWindow.class));

    }

    private SingleOutputStreamOperator<TradeProvinceOrderWindow> extendDimInfo(SingleOutputStreamOperator<TradeProvinceOrderWindow> ds) {
        return AsyncDataStream.unorderedWait(
                ds,
                new MyAsyncFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public String getTable() {
                        return "dim_base_province";
                    }

                    @Override
                    public String getId(TradeProvinceOrderWindow input) {
                        return input.getProvinceId();
                    }

                    @Override
                    protected void extendDimInfo(TradeProvinceOrderWindow data, JSONObject dimInfo) {
                        data.setProvinceName(dimInfo.getString("NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );
    }

    private SingleOutputStreamOperator<TradeProvinceOrderWindow> windowAndAgg(SingleOutputStreamOperator<TradeProvinceOrderWindow> ds) {
        // 1 创建水印策略
        WatermarkStrategy<TradeProvinceOrderWindow> strategy = WatermarkStrategy.<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .keyBy(TradeProvinceOrderWindow::getProvinceId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow t1, TradeProvinceOrderWindow t2) throws Exception {
                        t2.getIds().addAll(t1.getIds());
                        t2.setOrderAmount(t2.getOrderAmount().add(t1.getOrderAmount()));
                        return t2;
                    }
                }, new WindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeProvinceOrderWindow> input, Collector<TradeProvinceOrderWindow> out) throws Exception {
                        TradeProvinceOrderWindow result = input.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setOrderCount((long) result.getIds().size());
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TradeProvinceOrderWindow> toTradeProvinceOrderWindow(DataStreamSource<String> ds) {
        return ds.map(new RichMapFunction<String, TradeProvinceOrderWindow>() {
            @Override
            public TradeProvinceOrderWindow map(String s) throws Exception {
                JSONObject obj = JSON.parseObject(s);
                HashSet<String> ids = new HashSet<>();
                ids.add(obj.getString("order_id"));
                return TradeProvinceOrderWindow.builder()
                        .orderDetailId(obj.getString("id"))
                        .ids(ids)
                        .provinceId(obj.getString("province_id"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
            }
        }).filter(t -> t.getProvinceId() != null)
                .keyBy(TradeProvinceOrderWindow::getOrderDetailId)
                .process(new KeyedProcessFunction<String, TradeProvinceOrderWindow, TradeProvinceOrderWindow>() {

                    private ValueState<TradeProvinceOrderWindow> flagData;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagData = getRuntimeContext().getState(new ValueStateDescriptor<TradeProvinceOrderWindow>("flagData", TradeProvinceOrderWindow.class));
                    }

                    @Override
                    public void processElement(TradeProvinceOrderWindow value, KeyedProcessFunction<String, TradeProvinceOrderWindow, TradeProvinceOrderWindow>.Context ctx, Collector<TradeProvinceOrderWindow> out) throws Exception {
                        TradeProvinceOrderWindow lagData = flagData.value();
                        flagData.update(value);
                        if (lagData == null) {
                            out.collect(value);
                        } else {
                            value.setOrderAmount(value.getOrderAmount().subtract(lagData.getOrderAmount()));
                            out.collect(value);
                        }
                    }
                });
    }
}
